package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Banner;
import cn.wolfcode.luowowo.query.BannerQuery;
import cn.wolfcode.luowowo.repository.BannerRepository;
import cn.wolfcode.luowowo.service.IBannerService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService {

    @Autowired
    private BannerRepository bannerRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public Banner get(String id) {
        return bannerRepository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> listAll() {
        return bannerRepository.findAll();
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public void save(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {
        //查询条件
        Query query = new Query();
        //高级查询条件
        /*if(qo.getTypeId() == Banner.TYPE_TRAVEL){
            query.addCriteria(Criteria.where(""))
        }*/

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");
        Page<Banner> page = DBHelper.query(template, Banner.class, query, pageable);
        return page;
    }

    @Override
    public void saveOrUpdate(Banner banner) {
        if (StringUtils.hasLength(banner.getId())) {
            bannerRepository.save(banner);
        }else {
            banner.setId(null);
            bannerRepository.save(banner);
        }
    }

    @Override
    public void changeState(String id, int state) {
        Banner banner = this.get(id);
        banner.setState(state);
        this.update(banner);
    }

    @Override
    public List<Banner> queryTop5Travel(int typeTravel) {
        Pageable pageable = PageRequest.of(0,5, Sort.Direction.DESC,"sequence");
        return bannerRepository.findByTypeAndState(typeTravel,Banner.STATE_NORMAL,pageable);
    }
}
